package cn.sybgt;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import jse.log.Log;
import jse.log.Logs;

public class JPush {

	public static void push(String appkey,String appsecret,String title,String message,
			String registration_id,boolean iskf) {
		Log LOG=Logs.get();
		JPushClient jpushClient = new JPushClient(appsecret, appkey,null,ClientConfig.getInstance());
	    PushPayload payload = buildPushObject_all_alert(title,message,registration_id,iskf);
	    try {
	        PushResult result = jpushClient.sendPush(payload);
	        LOG.info("Got result - " + result);
	    } catch (APIConnectionException e) {
	        LOG.error("Connection error, should retry later", e);
	    } catch (APIRequestException e) {
	        LOG.error("Should review the error, and fix the request", e);
	        LOG.info("HTTP Status: " + e.getStatus());
	        LOG.info("Error Code: " + e.getErrorCode());
	        LOG.info("Error Message: " + e.getErrorMessage());
	    }
	}

	public static PushPayload buildPushObject_all_alert(String title,String message,String registration_id,boolean iskf) {
		Options options=Options.sendno(100000);
		options.setTimeToLive(3600);
		options.setApnsProduction(iskf);//开发环境
		Builder build=PushPayload.newBuilder()
        .setPlatform(Platform.all());
		if(registration_id!=null) {
			build.setAudience(Audience.registrationId(registration_id));
		}else {
			build.setAudience(Audience.all());
		}
		return build.setNotification(Notification.android(message, title, null))
                .setOptions(options)
                .build();
    }
}
